package com.netflexitysolutions.amazonws.ec2.internal.operations;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import com.amazonaws.ec2.doc._2009_04_04.AttachmentSetItemResponseType;
import com.amazonaws.ec2.doc._2009_04_04.DescribeVolumesResponseType;
import com.amazonaws.ec2.doc._2009_04_04.DescribeVolumesSetItemResponseType;
import com.amazonaws.ec2.doc._2009_04_04.DescribeVolumesSetItemType;
import com.amazonaws.ec2.doc._2009_04_04.DescribeVolumesSetType;
import com.amazonaws.ec2.doc._2009_04_04.DescribeVolumesType;
import com.netflexitysolutions.amazonws.ec2.AttachmentInfo;
import com.netflexitysolutions.amazonws.ec2.AttachmentStatus;
import com.netflexitysolutions.amazonws.ec2.EC2;
import com.netflexitysolutions.amazonws.ec2.Volume;
import com.netflexitysolutions.amazonws.ec2.internal.ModelUtil;

public class DescribeVolumesOperation extends ObjectSetOperationExecutor<DescribeVolumesType, List<Volume>> {

	public DescribeVolumesOperation(EC2 ec2, Set<String> objectIds) {
		super(ec2, objectIds);
	}

	@Override
	protected List<Volume> call(DescribeVolumesType request) {
		request.setVolumeSet(createVolumeSetElement());
		
		DescribeVolumesResponseType response = getEC2().getService().describeVolumes(request);
		
		List<Volume> result =  new ArrayList<Volume>();
		if (response.getVolumeSet() != null) {
			List<DescribeVolumesSetItemResponseType> list = response.getVolumeSet().getItem();
			for (DescribeVolumesSetItemResponseType item : list) {
				result.add(toDomainModel(item));
			}
		}
		
		return result;
	}

	private Volume toDomainModel(DescribeVolumesSetItemResponseType item) {
		List<AttachmentInfo> attachements = new ArrayList<AttachmentInfo>();
		if(item.getAttachmentSet() != null) {
			List<AttachmentSetItemResponseType> xmlAttachements = item.getAttachmentSet().getItem();
			for (AttachmentSetItemResponseType xmlAttachement : xmlAttachements) {
				AttachmentInfo attachement = new AttachmentInfo(xmlAttachement.getVolumeId(), xmlAttachement.getInstanceId(),
						xmlAttachement.getDevice(), AttachmentStatus.attachmentStatusForName(xmlAttachement.getStatus()), 
						ModelUtil.toDomainType(xmlAttachement.getAttachTime()));
				attachements.add(attachement);
			}
		}
		Volume volume = new Volume(item.getVolumeId(), item.getSize(), item.getSnapshotId(), item.getAvailabilityZone(),
				item.getStatus(), ModelUtil.toDomainType(item.getCreateTime()), attachements);	
		return volume;
	}

	private DescribeVolumesSetType createVolumeSetElement() {
		DescribeVolumesSetType element = new DescribeVolumesSetType();
		List<DescribeVolumesSetItemType> list = element.getItem();
		for (String volumeId : objectIds) {
			DescribeVolumesSetItemType item = new DescribeVolumesSetItemType();
			item.setVolumeId(volumeId);
			list.add(item);
		}
		return element;
	}

	
}
